package cn.com.anypay.manager.miaoma.suantaiqrcode.handler.impl;

import cn.com.anypay.manager.miaoma.suantaiqrcode.SuantaiQrcodeEntity;
import cn.com.anypay.manager.miaoma.suantaiqrcode.handler.AbstractQrCodeHandler;
import cn.com.anypay.manager.common.response.ApiResponse;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

/**
 * 默认二维码处理器
 *
 * 用于处理未知类型的二维码或者向后兼容的场景
 * 会尝试从JSON中获取url字段进行跳转
 */
@Slf4j
@Component
public class DefaultQrCodeHandler extends AbstractQrCodeHandler {

    private static final String HANDLER_NAME = "DefaultQrCodeHandler";

    @Override
    public ApiResponse<Object> handle(SuantaiQrcodeEntity qrcode, String id) {
        logHandleStart(id);

        if (!isValidContent(qrcode.getContent())) {
            logHandleComplete(id, "Content is empty");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "Content is empty");
        }

        // 尝试按照原有逻辑处理：从JSON中提取url字段
        try {
            JsonNode content = parseJsonContent(qrcode.getContent());
            if (content != null) {
                String url = extractUrl(content);
                if (url != null && !url.trim().isEmpty()) {
                    logHandleComplete(id, "Using fallback URL extraction, redirecting to: " + url);
                    return createRedirectResponse(url);
                }
            }

            // 如果无法解析JSON，尝试将content直接当作URL处理
            String directUrl = qrcode.getContent().trim();
            if (isValidUrl(directUrl)) {
                logHandleComplete(id, "Using content as direct URL: " + directUrl);
                return createRedirectResponse(directUrl);
            }

            log.warn("[{}] Unable to extract valid URL from QR code content, id: {}, content: {}",
                     getHandlerName(), id, qrcode.getContent());
            logHandleComplete(id, "No valid URL found");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "No valid URL found in content");

        } catch (Exception e) {
            log.error("[{}] Error processing QR code, id: {}", getHandlerName(), id, e);
            logHandleComplete(id, "Processing error: " + e.getMessage());
            return createErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, "Processing error");
        }
    }

    /**
     * 从JSON内容中提取URL
     *
     * @param content JSON内容
     * @return URL字符串
     */
    private String extractUrl(JsonNode content) {
        // 尝试多种可能的字段名
        String[] urlFields = {"url", "targetUrl", "link", "href"};

        for (String field : urlFields) {
            JsonNode urlNode = content.get(field);
            if (urlNode != null && !urlNode.asText().trim().isEmpty()) {
                return urlNode.asText();
            }
        }

        return null;
    }

    /**
     * 简单的URL格式验证
     *
     * @param url URL字符串
     * @return 是否为有效URL
     */
    private boolean isValidUrl(String url) {
        if (url == null || url.trim().isEmpty()) {
            return false;
        }

        String trimmedUrl = url.trim();
        return trimmedUrl.startsWith("http://") ||
               trimmedUrl.startsWith("https://") ||
               trimmedUrl.startsWith("data:") ||
               trimmedUrl.startsWith("//");
    }

    @Override
    public Integer getSupportedType() {
        // 默认处理器不绑定特定类型，返回null表示可以处理任何类型
        return null;
    }

    @Override
    public String getHandlerName() {
        return HANDLER_NAME;
    }
}